import { Cell } from "./cell";

class Fence {
  cells = [];
  specs; // sku
  title; // 规格名字
  id; // 主键

  constructor(specs) {
    this.specs = specs;
    this.title = specs[0].key;
    this.id = specs[0].key_id;
  }

  init() {
    this._initCells();
  }

  _initCells() {
    this.cells = [];
    this.specs.forEach((s) => {
      // 将重复数据删除
      const existed = this.cells.some((c) => {
        return c.id === s.value_id;
      });
      // 判断是否有重复id的数据
      if (existed) {
        return;
      }
      const cell = new Cell(s);
      this.cells.push(cell);
    });
  }

  setFenceSketch(skuList) {
    this.cells.forEach((c) => {
      this._setCellSkuImg(c, skuList);
    });
  }

  _setCellSkuImg(cell, skuList) {
    const specCode = cell.getCellCode();
    const matchedSku = skuList.find((s) => s.code.includes(specCode));
    if (matchedSku) {
      cell.skuImg = matchedSku.img;
    }
  }
}

export { Fence };
